<template>
  <div>
    <div class="headHint">活动课程明细</div>
    <el-row>
      <el-col :span="10">
        <el-input v-model="firstKeyWord" clearable style="width:200px" placeholder="请输入商品名称" @clear="handleFilter" @keyup.enter.native="handleFilter"/>
        <el-button type="primary" style="margin-left:10px;" @click="handleFilter">搜索</el-button>
      </el-col>
      <el-col :span="2" :offset="12">
        <el-button type="primary" icon="el-icon-plus" @click="addFirstActivity">新增活动</el-button>
      </el-col>
    </el-row>
    <el-table
      :data="detailTableData.slice((firstCurrentPage-1)*firstPageSize,firstCurrentPage*firstPageSize)"
      :default-sort="{prop: 'typeIndex', order: 'ascending'}"
      border
      style="width: 100%;text-align:center;margin-top:20px;">
      <el-table-column :index="typeIndex" type="index" label="编号" align="center"/>
      <el-table-column prop="courseName" label="商品名称" sortable column-key="name" align="center"/>
      <el-table-column prop="price" label="商品价格" sortable column-key="price" align="center"/>
      <el-table-column label="规则描述" sortable min-width="100" align="center">
        <template slot-scope="scope">
          <div v-if="kind === 'cutPrice'">
            <span>砍价低价为{{ scope.row.cutPriceFloor }}且最大砍价值为{{ scope.row.cutPriceMax }}元最小砍价值为{{ scope.row.cutPriceMin }}元</span>
          </div>
          <div v-if="kind === 'quickSell'">
            <span>最大减少时间为{{ scope.row.maxMs }}最小减少时间为{{ scope.row.minMs }}且人数限制在{{ scope.row.astrict }}内</span>
          </div>
          <div v-if="kind === 'groupPurchase'">
            <span>{{ scope.row.ruleDescribe }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="活动时间" sortable column-key="startTime" width="300" align="center">
        <template slot-scope="scope">
          <div>开始时间：{{ scope.row.startTimeStr }}</div>
          <div>结束时间：{{ scope.row.endTimeStr }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="availableAmount" label="课程数量" sortable column-key="availableAmount" align="center">
        <template slot-scope="scope">
          <span>共{{ scope.row.availableAmount }}件，{{ scope.row.usedAmount === 0 ? '该课程暂无订单' : '该课程有' + scope.row.usedAmount + '订单' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="100" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-edit" @click="editWares(scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteWares(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="block" style="margin:20px 0;">
      <el-pagination
        :current-page="firstCurrentPage"
        :page-sizes="[5, 10, 20]"
        :page-size="firstPageSize"
        :total="detailTableData.length"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
    <!-- 编辑/新增弹框 -->
    <el-dialog :visible.sync="waresdialogVisible" :before-close="waresHandleClose" title="提示" width="60%">
      <el-form ref="waresForm" :model="waresForm" :rules="dialogRules" label-width="150px">
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="商品类型:" prop="itemType">
              <el-radio-group v-model="itemType" size="small">
                <el-radio-button label="1">课程</el-radio-button>
                <el-radio-button label="0">班级</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="明细类型:" prop="type">
              <span>{{ kind === 'cutPrice' ? '帮砍价' : kind === 'groupPurchase' ? '多人拼团' : kind === 'quickSell' ? '秒杀' : '竞答' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="商品名称：">
              <el-input v-model="waresForm.courseName" @focus="showInnerDialog"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="课程数量：" prop="availableAmount">
              <el-input v-model="waresForm.availableAmount" placeholder="请输入课程数量"/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="课程单价：" prop="price">
              <el-input v-model="waresForm.price" placeholder="请输入课程单价">
                <template slot="prepend">￥</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="开始时间：" prop="startTime">
              <el-date-picker
                v-model="waresForm.startTime"
                type="datetime"
                placeholder="选择日期时间"
                style="width:100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="结束时间：" prop="endTime">
              <el-date-picker
                v-model="waresForm.endTime"
                type="datetime"
                placeholder="选择日期时间"
                style="width:100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item v-if="kind==='quickSell'" label="提前抢购：" prop="purchase">
              <el-radio-group v-model="waresForm.purchase" size="small">
                <el-radio-button label="1">是</el-radio-button>
                <el-radio-button label="0">否</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="kind!=='quickSell'" label="限时设定:" prop="timeLimit">
              <el-input v-model="waresForm.timeLimit" placeholder="请输入限时时间">
                <template slot="append">小时</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item v-if="kind==='quickSell'" label="课程描述：" prop="description">
              <el-input v-model="waresForm.description" placeholder="请输入描述"/>
            </el-form-item>
            <el-form-item v-if="kind==='cutPrice'" label="砍价底价:" prop="cutPriceFloor">
              <el-input v-model="waresForm.cutPriceFloor" placeholder="请输入砍价底价">
                <template slot="prepend">￥</template>
              </el-input>
            </el-form-item>
            <el-form-item v-if="kind==='groupPurchase'" label="规则描述:" prop="ruleDescribe">
              <el-input v-model="waresForm.ruleDescribe" placeholder="请输入规则描述">
                <!--<template slot="prepend">￥</template>-->
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item v-if="kind==='quickSell'" label="减少时间(max):" prop="maxMs">
              <el-input v-model="waresForm.maxMs" placeholder="请输入减少时间">
                <template slot="append">毫秒</template>
              </el-input>
            </el-form-item>
            <el-form-item v-if="kind==='cutPrice'" label="砍价最大值:" prop="cutPriceMax">
              <el-input v-model="waresForm.cutPriceMax" placeholder="请输入砍价最大值">
                <template slot="prepend">￥</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item v-if="kind==='quickSell'" label="减少时间(min):" prop="minMs">
              <el-input v-model="waresForm.minMs" placeholder="请输入减少时间">
                <template slot="append">毫秒</template>
              </el-input>
            </el-form-item>
            <el-form-item v-if="kind==='cutPrice'" label="砍价最小值:" prop="cutPriceMin">
              <el-input v-model="waresForm.cutPriceMin" placeholder="请输入砍价最小值">
                <template slot="prepend">￥</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item v-if="kind==='quickSell'" label="人数限制：" prop="astrict">
              <el-input v-model="waresForm.astrict" placeholder="请输入限几人"/>
            </el-form-item>
            <el-form-item v-if="kind==='cutPrice'" label="商品描述：">
              <el-input v-model="waresForm.commodityDescribe" placeholder="请输入商品描述"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div v-if="kind==='groupPurchase'" class="group_tab_box">
        <div class="group_tab_head">
          <span>价格设置</span>
          <el-button type="primary" class="group_tab_btn" icon="el-icon-plus" size="small" @click="addPriceSet">新增</el-button>
        </div>
        <el-table
          :data="groupPriceSetData.slice((priceCurrentPage-1)*pricePageSize,priceCurrentPage*pricePageSize)"
          border
          style="width: 100%;text-align:center;margin-top:10px;"
        >
          <el-table-column prop="id" label="编号" align="center">
            <template slot-scope="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="tuxedoNumber" label="参团人数" align="center"/>
          <el-table-column prop="markDownSet" label="减价设置" align="center"/>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="priceSetEdit(scope.row)">编辑</el-button>
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="priceSetDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 价格设置表格分页 -->
        <div class="block" style="margin:20px 0;">
          <el-pagination
            :current-page="priceCurrentPage"
            :page-sizes="[5, 10, 20]"
            :page-size="pricePageSize"
            :total="groupPriceSetData.length"
            background
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="priceCurrentChange"
            @size-change="priceSizeChange"
          />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editWaresCancel">取 消</el-button>
        <el-button type="primary" @click="editWaresConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 内层课程弹框 -->
    <el-dialog :visible.sync="waresInnerVisible" append-to-body width="45%" title="课程列表">
      <div>
        <el-input v-model="innerWaresKeyWord" clearable style="width:200px" placeholder="请输入课程名称" @clear="innerWaresKeyWordHandleFilter" @keyup.enter.native="innerWaresKeyWordHandleFilter"/>
        <el-button type="primary" style="margin-left:10px;" @click="innerWaresKeyWordHandleFilter">搜索</el-button>
      </div>
      <!--活动 课程列表-->
      <el-table
        :data="waresTableData"
        :default-sort="{prop: 'waresSerial', order: 'ascending'}"
        border
        style="width: 100%;text-align:center;margin-top:20px;"
      >
        <el-table-column label="选择" align="center" width="80">
          <template slot-scope="scope">
            <el-radio :label="scope.$index + 1" v-model="radioSelected" @change="getTemplateRow(scope.row)"/>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="课程名称" sortable column-key="title" align="center"/>
        <el-table-column prop="oraCategoryName" label="课程分类" sortable column-key="oraCategoryName" align="center"/>
        <el-table-column prop="price" label="价格" sortable column-key="price" align="center" width="130">
          <template slot-scope="scope">
            <span>￥{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="market" label="销售数量" sortable column-key="market" align="center"/>
      </el-table>
      <!-- 课程分页 -->
      <div class="block" style="margin:20px 0;">
        <el-pagination
          :current-page="innerCurrentPage"
          :page-sizes="[5, 10, 20]"
          :page-size="innerPageSize"
          :total="innerTotal"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="innerCurrentChange"
          @size-change="innerSizeChange"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="innerWaresCancel">取 消</el-button>
        <el-button type="primary" @click="innerWaresConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 价格设置新增弹框 -->
    <el-dialog :visible.sync="priveSetVisible" append-to-body width="45%" title="等级价格设置">
      <el-form ref="priceSetForm" :model="priceSetForm" :rules="priceSetRules" label-width="300px">
        <el-form-item label="参团人数:" prop="tuxedoNumber">
          <el-input
            v-model="priceSetForm.tuxedoNumber"
            placeholder="请输入参团人数"
            style="width:300px;"
          />
        </el-form-item>
        <el-form-item label="减价设置:" prop="markDownSet">
          <el-input v-model="priceSetForm.markDownSet" placeholder="元/" style="width:300px;"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="priveDialogCancel">取 消</el-button>
        <el-button type="primary" @click="priveDialogConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import {getTenantId, getUserName} from '@/utils/auth'
  import {addOrUpdateActivityDetail, addOrUpdatePriceset, deleteActivityDetailById, deletePriceset, getActivityDetailById, getActivityGoodsDetail, getClassRoomList, getCourseList, getPricesetById, getPricesetList} from '@/api/tinysale/addActivity'

  export default {
    props: {
      activityId: {
        type: String,
        default() {
          return ''
        }
      },
      kind: {
        type: String,
        default() {
          return ''
        }
      }
    },
    data() {
      return {
        firstKeyWord: '',
        itemType: 1,
        detailTableData: [],
        filterData: [],
        // 分页数据
        firstCurrentPage: 1,
        firstPageSize: 5,
        waresdialogVisible: false,
        waresInnerVisible: false,
        priveSetVisible: false,
        innerWaresKeyWord: '',
        radioSelected: '',
        waresForm: {},
        priceSetForm: {
          activityDetailId: '',
          tuxedoNumber: '',
          markDownSet: ''
        },
        dialogRules: {
          // courseName: [
          //   { required: true, message: '请输入商品名称', trigger: 'focus' }
          // ],
          availableAmount: [
            {required: true, message: '请输入课程数量', trigger: 'blur'}
          ],
          price: [
            {required: true, message: '请输入课程单价', trigger: 'blur'}
          ],
          startTime: [
            {required: true, message: '请输入开始时间', trigger: 'blur'}
          ],
          endTime: [
            {required: true, message: '请输入结束时间', trigger: 'blur'}
          ],
          description: [
            {required: true, message: '请输入商品描述', trigger: 'blur'}
          ],
          maxMs: [
            {required: true, message: '请输入减少时间', trigger: 'blur'}
          ],
          minMs: [
            {required: true, message: '请输入减少时间', trigger: 'blur'}
          ],
          astrict: [
            {required: true, message: '请输入限制人数', trigger: 'blur'}
          ],
          timeLimit: [
            {required: true, message: '请输入限时时间', trigger: 'blur'}
          ],
          cutPriceFloor: [
            {required: true, message: '请输入砍价底价', trigger: 'blur'}
          ],
          cutPriceMax: [
            {required: true, message: '请输入砍价最大值', trigger: 'blur'}
          ],
          cutPriceMin: [
            {required: true, message: '请输入砍价最小值', trigger: 'blur'}
          ],
          ruleDescribe: [
            {required: true, message: '请输入规则描述', trigger: 'blur'}
          ]
        },
        priceSetRules: {
          tuxedoNumber: [
            {required: true, message: '请输入参团人数', trigger: 'blur'}
          ],
          markDownSet: [
            {required: true, message: '请输入减价设置', trigger: 'blur'}
          ]
        },
        waresTableData: [],
        groupPriceSetData: [],
        waresRadio: '0',
        // 外层价格设置表格分页
        priceCurrentPage: 1,
        pricePageSize: 5,
        // 内层课程弹框分页
        innerCurrentPage: 1,
        innerPageSize: 5,
        innerTotal: 0
      }
    },
    created() {
      this.getData()
    },
    methods: {
      // 动态生成表格编号
      typeIndex(index) {
        return index + (this.firstCurrentPage - 1) * this.firstPageSize + 1
      },
      getData() {
        getActivityGoodsDetail(this.activityId).then(res => {
          this.detailTableData = res.data.items;

          this.filterData = res.data.items
        })
      },
      handleFilter() {
        this.detailTableData = this.filterData.filter(item => {
          if (this.firstKeyWord && item.courseName.toLocaleLowerCase().indexOf(this.firstKeyWord.toLocaleLowerCase()) < 0) return false;
          return true
        })
      },
      // 分页设置
      handleCurrentChange(arg) {
        this.firstCurrentPage = arg
      },
      handleSizeChange(arg) {
        this.firstPageSize = arg
      },
      waresHandleClose(done) {
        this.$refs.waresForm.resetFields();
        this.radioSelected = '';
        done()
      },
      // 新增活动事件
      addFirstActivity() {
        this.$emit('save');
        setTimeout(() => {
          if (this.activityId) {
            this.waresdialogVisible = true
          }
        }, 200);
        this.waresForm = {};
        this.groupPriceSetData = []
      },
      addPriceSet() {//新增课程明细价格设置
        this.$refs.waresForm.validate((valid) => {
          if (valid) {
            if (this.waresForm.id) {
              console.log(this.waresForm.id);
              this.priceSetForm.activityDetailId = this.waresForm.id;
              this.priveSetVisible = true
            } else {
              this.waresForm.kind = this.kind;
              this.waresForm.creator = getUserName();
              this.waresForm.tenantId = getTenantId();
              this.waresForm.surplusAmount = this.waresForm.availableAmount;
              this.waresForm.usedAmount = 0;
              addOrUpdateActivityDetail(this.waresForm).then(res => {
                this.waresForm.id = res.data.id;
                this.priceSetForm.activityDetailId = res.data.id;
                this.priveSetVisible = true
              })
            }
          } else {
            return false
          }
        })
      },
      priceSetEdit(row) {
        this.priveSetVisible = true;
        getPricesetById(row.id).then(res => {
          this.priceSetForm = res.data.item
        })
      },
      priceSetDelete(row) {
        this.$confirm('确认要删除此价格设置吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          deletePriceset(row.id).then(() => {
            this.$notify({
              title: '成功',
              message: '成功',
              type: 'success',
              duration: 2000
            });
            this.getPriceset(row.activityDetailId)
          })
        })
      },
      priveDialogConfirm() {
        this.$refs.priceSetForm.validate((valid) => {
          if (valid) {
            if (!this.priceSetForm.id) {
              this.priceSetForm.creator = getUserName();
              this.priceSetForm.tenantId = getTenantId()
            }
            addOrUpdatePriceset(this.priceSetForm).then(() => {
              this.$notify({
                title: '成功',
                message: '成功',
                type: 'success',
                duration: 2000
              });
              this.priveSetVisible = false;
              this.getPriceset(this.priceSetForm.activityDetailId);
              this.priceSetForm = {activityDetailId: '', tuxedoNumber: '', markDownSet: ''};
              this.$refs.priceSetForm.resetFields()
            })
          } else {
            return false
          }
        })
      },
      priveDialogCancel() {
        this.priveSetVisible = false;
        this.$refs.priceSetForm.resetFields()
      },
      // 外层价格设置表格分页设置
      priceCurrentChange(arg) {
        this.priceCurrentPage = arg
      },
      priceSizeChange(arg) {
        this.pricePageSize = arg
      },
      // 显示内层弹框
      showInnerDialog() {
        this.waresInnerVisible = true;
        this.waresForm.activityId = this.activityId;
        this.getCourseList()
      },
      getCourseList() {
        console.log(this.itemType);
        if (this.itemType === '0') {

          const params = {};
          params.page = this.innerCurrentPage;
          params.pageSize = this.innerPageSize;
          params.tenantId = getTenantId();
          params.name = this.innerWaresKeyWord;
          getClassRoomList(params).then(res => {
            this.waresTableData = res.data.items;
            this.innerTotal = res.data.total
          })
        } else {
          const params = {};
          params.page = this.innerCurrentPage;
          params.pageSize = this.innerPageSize;
          params.tenantId = getTenantId();
          params.name = this.innerWaresKeyWord;
          getCourseList(params).then(res => {
            this.waresTableData = res.data.items;
            this.innerTotal = res.data.total
          })
        }
        this.innerWaresKeyWord = ''
      },
      innerWaresKeyWordHandleFilter() {
        this.getCourseList()
      },
      // 内层课程分页设置
      innerCurrentChange(arg) {
        this.innerCurrentPage = arg;
        this.getCourseList()
      },
      innerSizeChange(arg) {
        this.innerPageSize = arg;
        this.getCourseList()
      },
      getTemplateRow(row) {
        this.waresForm.courseName = row.title;
        this.waresForm.courseId = row.id;
        this.waresForm.originalPrice = row.price
      },
      // 添加课程确定
      innerWaresConfirm() {
        this.radioSelected = '';
        this.innerWaresKeyWord = '';
        this.waresInnerVisible = false
      },
      // 添加课程取消
      innerWaresCancel() {
        this.waresForm.courseName = '';
        this.waresForm.courseId = '';
        this.waresForm.originalPrice = '';
        this.radioSelected = '';
        this.innerWaresKeyWord = '';
        this.waresInnerVisible = false
      },
      // 编辑商品信息
      editWares(row) {
        this.waresdialogVisible = true;
        getActivityDetailById(row.id).then(res => {
          this.waresForm = res.data.item;
        });
        if (this.kind === 'groupPurchase') {
          this.getPriceset(row.id)
        }
      },
      getPriceset(activityDetailId) {
        getPricesetList(activityDetailId).then(res => {
          this.groupPriceSetData = res.data.items
        })
      },
      editWaresCancel() {
        this.waresdialogVisible = false;
        this.waresForm = {};
        this.groupPriceSetData = []
      },
      editWaresConfirm() {//编辑商品确认
        this.$refs.waresForm.validate((valid) => {
          if (valid) {
            if (!this.waresForm.courseId) {
              this.$message.error('请选择商品!')
            } else {
              if (!this.waresForm.id) {
                this.waresForm.kind = this.kind;
                this.waresForm.creator = getUserName();
                this.waresForm.tenantId = getTenantId()
              }
              this.waresForm.surplusAmount = this.waresForm.availableAmount;
              this.waresForm.usedAmount = 0;
              addOrUpdateActivityDetail(this.waresForm).then(() => {
                this.getData();
                this.$notify({
                  title: '成功',
                  message: '成功',
                  type: 'success',
                  duration: 2000
                });
                this.waresForm = {};
                this.groupPriceSetData = [];
                this.waresdialogVisible = false
              })
            }
          } else {
            return false
          }
        })
      },
      // 删除事件
      deleteWares(row) {
        this.$confirm('确定要删除该商品吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteActivityDetailById(row.id).then(() => {
            this.$notify({
              title: '成功',
              message: '成功',
              type: 'success',
              duration: 2000
            });
            this.getData()
          })
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .headHint {
    color: rgb(52, 172, 228);
    padding: 10px 30px;
    background: #ebf4ff;
    margin: 20px 0;
    overflow: hidden;
  }

  .group_tab_box {
    padding: 10px 30px;

    .group_tab_head {
      padding: 10px 0;

      span {
        font-size: 18px;
        color: #0d8af0;
      }

      .group_tab_btn {
        float: right;
        margin-top: -6px;
      }
    }
  }
</style>

